package com.maistars.spider.security.service.impl;

import com.maistars.spider.repository.security.mapper.*;
import com.maistars.spider.repository.security.model.RolePO;
import com.maistars.spider.repository.security.model.UserPO;
import com.maistars.spider.repository.security.model.UserRolePO;
import com.maistars.spider.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dhr
 * @date 2022/7/10 10:18
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserPO getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public UserPO getUserByUsername(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public UserPO getUserByPhone(String phone) {
        UserPO userPO = new UserPO();
        userPO.setPhone(phone);
        return userMapper.selectByCondition(userPO);
    }

    @Override
    public List<UserPO> getAllUser() {
        return userMapper.selectAll();
    }

    public UserPO getUserDetail(Integer userId) {
        List<RolePO> rolePOS = new ArrayList<>();
        UserPO user = userMapper.selectUserDetailByUserId(userId);
        return user;
    }

    @Override
    public void addUser(UserPO userPO) {
        userMapper.insert(userPO);
    }

    @Override
    public void updateUser(UserPO userPO) {
        userMapper.updateByIdSelective(userPO);
    }

    @Override
    public void addUserRole(Integer userId, Integer roleId) {
        UserRolePO userRolePO = new UserRolePO();
        userRolePO.setUserId(userId);
        userRolePO.setRoleId(roleId);
        userRoleMapper.insert(userRolePO);
    }

    @Override
    public UserPO getUserDetailByUsername(String userName) {
        UserPO user = getUserByUsername(userName);
        if (user != null) {
            // 查询角色
            user = userMapper.selectUserDetailByUserId(user.getUserId());
        }
        return user;
    }
}
